/* eslint-disable @typescript-eslint/no-unsafe-assignment */
import { BadRequestException, Injectable } from '@nestjs/common';
import { FindOptionsWhere, Like, Repository } from 'typeorm';
import { Poet } from './entities/poet.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { CreateDto } from './dto/create.dto';
import { UpdateDto } from './dto/update.dto';
import { ListDto } from './dto/list.dto';
import { paginatedScrape } from 'src/common/utils/scrape';
import { scrapePoetId } from 'src/common/utils/scrape/poet';
import { batchScrapePoetUrls } from 'src/common/utils/scrape/poet-ext';
import { createReadStream } from 'fs';
import { createInterface } from 'readline';

@Injectable()
export class PoetService {
  @InjectRepository(Poet)
  private readonly poetRepository: Repository<Poet>;

  async create(createDto: CreateDto) {
    const isExist = await this.poetRepository.findOne({
      where: {
        name: createDto.name,
      },
    });
    if (isExist) {
      throw new BadRequestException('诗人已存在');
    } else {
      return await this.poetRepository.save(createDto);
    }
  }

  async delete(id: number) {
    const isExist = await this.poetRepository.findOne({
      where: {
        id,
      },
    });
    if (isExist) {
      return await this.poetRepository.delete(id);
    } else {
      throw new BadRequestException('诗人不存在');
    }
  }

  async update(updateDto: UpdateDto) {
    const isExist = await this.poetRepository.findOne({
      where: {
        id: updateDto.id,
      },
    });
    if (isExist) {
      return await this.poetRepository.update(updateDto.id, updateDto);
    } else {
      throw new BadRequestException('诗人不存在');
    }
  }

  async info(id: number) {
    console.log(id);
    const res = await this.poetRepository.findOne({
      where: {
        id,
      },
      relations: {
        poems: {
          poemTags: true,
        },
      },
      select: {
        poems: {
          id: true,
          title: true,
          content: true,
          poemTags: {
            id: true,
            name: true,
          },
        },
      },
    });
    if (!res) {
      throw new BadRequestException('诗人不存在');
    }
    return res;
  }

  async list(listDto: ListDto) {
    const { page, limit, name, ...resetListDto } = listDto;
    const query: FindOptionsWhere<Omit<ListDto, 'page' | 'limit'>> =
      resetListDto;
    if (name) {
      query.name = Like(`%${name}%`);
    }
    const [list, total] = await this.poetRepository.findAndCount({
      where: query,
      skip: (page - 1) * limit,
      take: limit,
    });
    return {
      list,
      total,
      page,
      limit,
    };
  }

  async scrapePoetIds() {
    try {
      const filePath = 'src/scrape-data/poet-ids.txt';
      await paginatedScrape(
        scrapePoetId,
        'https://aspoem.com/zh-Hans/author/list',
        Math.ceil(705 / 12),
        // Math.ceil(1),
        filePath,
        500,
      );
      return '爬取成功';
    } catch (error) {
      throw new BadRequestException(error);
    }
  }

  async crawlContent() {
    return batchScrapePoetUrls(
      'src/scrape-data/poet-ids.txt',
      'src/scrape-data/poet-content.txt',
      500,
    );
  }

  async processPoetsFromFile(filePath: string) {
    const fileStream = createReadStream(filePath);
    const rl = createInterface({
      input: fileStream,
      crlfDelay: Infinity,
    });

    let processedCount = 0;
    let createdCount = 0;
    const updatedCount = 0;

    for await (const line of rl) {
      try {
        const poetData = JSON.parse(line);
        // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
        const { name, dynasty, description, birthday, deadday, wiki } =
          poetData;

        // 检查诗人是否存在
        let poet = await this.poetRepository.findOne({ where: { name } });

        if (poet) {
          // // 如果存在则更新数据
          // // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
          // poet.dynasty = dynasty || poet.dynasty;
          // // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
          // poet.description = description || poet.description;
          // // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
          // poet.birthday = birthday || poet.birthday;
          // // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
          // poet.deadday = deadday || poet.deadday;
          // // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
          // poet.wiki = wiki || poet.wiki;
          // await this.poetRepository.save(poet);
          // updatedCount++;
          console.log();
        } else {
          // 如果不存在则创建新诗人
          poet = this.poetRepository.create({
            // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
            name,
            // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
            dynasty,
            // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
            description,
            // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
            birthday,
            // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
            deadday,
            // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
            wiki,
          });
          await this.poetRepository.save(poet);
          createdCount++;
        }

        processedCount++;
      } catch (error) {
        console.error(`处理行数据时出错: ${line}`, error);
      }
    }

    console.log(`处理完成，共处理了 ${processedCount} 条数据`);
    console.log(`新建诗人: ${createdCount} 个`);
    console.log(`更新诗人: ${updatedCount} 个`);
  }
}
